<!-- 表格合并 -->
<template>
  <el-table :data="sortedData" :span-method="spanMethod" border style="width: 100%">
    <el-table-column prop="id" label="ID" width="180" />
    <el-table-column prop="name" label="Name" />
    <el-table-column prop="amount1" sortable label="Amount 1" />
    <el-table-column prop="amount2" sortable label="Amount 2" />
    <el-table-column prop="amount3" sortable label="Amount 3" />
  </el-table>
</template>
<script setup>
import { ref } from 'vue'
const data = ref([
  {
    id: '12987122',
    name: 'Tom',
    amount1: '234',
    amount2: '3.2',
    amount3: 10,
  },
  {
    id: '12987123',
    name: 'Tom',
    amount1: '165',
    amount2: '4.43',
    amount3: 12,
  },
  {
    id: '12987122',
    name: 'Tom1',
    amount1: '234',
    amount2: '3.2',
    amount3: 10,
  },
  {
    id: '12987124',
    name: 'Tom',
    amount1: '324',
    amount2: '1.9',
    amount3: 9,
  },
  {
    id: '12987125',
    name: 'Tom',
    amount1: '621',
    amount2: '2.2',
    amount3: 17,
  },
  {
    id: '12987126',
    name: 'Tom',
    amount1: '539',
    amount2: '4.1',
    amount3: 15,
  },
])
function sortDataByFields(data, fields) {
  return data.slice().sort((a, b) => {
    for (let field of fields) {
      if (a[field] < b[field]) return -1
      if (a[field] > b[field]) return 1
    }
    return 0
  })
}
const mergeFields = ['id']
const sortedData = ref(sortDataByFields(data.value, mergeFields))

const spanMethod = ({ row, column, rowIndex }) => {
  // 只对需要合并的字段处理
  if (!mergeFields.includes(column.property)) return

  // 判断当前行是否是合并块的第一行
  let isFirst = true
  for (let i = 0; i < rowIndex; i++) {
    let same = true
    for (let field of mergeFields.slice(0, mergeFields.indexOf(column.property) + 1)) {
      if (sortedData.value[i][field] !== row[field]) {
        same = false
        break
      }
    }
    if (same) {
      isFirst = false
      break
    }
  }
  if (!isFirst) return { rowspan: 0, colspan: 0 }

  // 统计需要合并的行数
  let rowspan = 1
  for (let i = rowIndex + 1; i < sortedData.value.length; i++) {
    let same = true
    for (let field of mergeFields.slice(0, mergeFields.indexOf(column.property) + 1)) {
      if (sortedData.value[i][field] !== row[field]) {
        same = false
        break
      }
    }
    if (same) rowspan++
    else break
  }
  return { rowspan, colspan: 1 }
}
</script>
<style lang="scss" scoped></style>
